package org.jeecg.modules.api.wlhy.app;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.modules.api.wlhy.app.bean.*;
import org.jeecg.modules.api.wlhy.app.config.Config;
import org.jeecg.modules.api.wlhy.app.utils.HttpUtils;
import org.jeecg.modules.api.wlhy.app.utils.SM2Util;
import org.jeecg.modules.api.wlhy.app.utils.Util;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Component
public class AppUtils {


   /* @Value(value = "${APPID}")
    private String APPID;

    @Value(value = "${APPSECURITY}")
    private String APPSECURITY;

    @Value(value = "${EnterpriseSenderCode}")
    private String EnterpriseSenderCode;

    @Value(value = "${TJ_APPID}")
    private String TJ_APPID;

    @Value(value = "${TJ_APPSECURITY}")
    private String TJ_APPSECURITY;*/

//    private static final Logger LOGGER = LoggerFactory.getLogger(AppUtils.class);


    public static void init(HyConfig hyConfig) throws Exception {
//        if (hyConfig.getWzHbIzUse()) {
//            String appid = hyConfig.getWzHbAppid();
//            String secret =hyConfig.getWzHbSecret();
//            String code = hyConfig.getWzHbCode();
//            String st = hyConfig.getWzHbState();
//            InitReturnBean init = initMain(appid,secret,code, st);
//            HyConfigUtils.setInitReturnBean(init);
//        }
//        if (hyConfig.getWzTjIzUse()) {
//            String appid = hyConfig.getWzTjAppid();
//            String secret =hyConfig.getWzTjSecret();
//            String code = hyConfig.getWzTjCode();
//            String st = hyConfig.getWzTjState();
//            InitReturnBean init = initMain(appid,secret,code, st);
//            HyConfigUtils.setTjinitReturnBean(init);
//        }
//        if (hyConfig.getWzAhIzUse()) {
//            String appid = hyConfig.getWzAhAppid();
//            String secret =hyConfig.getWzAhSecret();
//            String code = hyConfig.getWzAhCode();
//            String st = hyConfig.getWzAhState();
//            InitReturnBean init = initMain(appid,secret,code, st);
//            HyConfigUtils.setAhinitReturnBean(init);
//        }
//        if (hyConfig.getWzJsIzUse()) {
//            String appid = hyConfig.getWzJsAppid();
//            String secret =hyConfig.getWzJsSecret();
//            String code = hyConfig.getWzJsCode();
//            String st = hyConfig.getWzJsState();
//            InitReturnBean init = initMain(appid,secret,code , st);
//            HyConfigUtils.setJsinitReturnBean(init);
//        }
    }

    /**
     * 初始化app
     * @return
     * @throws Exception
     */
    public static InitReturnBean initMain(String appid, String secret, String code , String st) throws Exception {
        InitReturnBean returnBean = new InitReturnBean();
        returnBean.setAppid(appid);
        returnBean.setSecret(secret);
        returnBean.setCode(code);

        Map<String,String> map = SM2Util.generateKeyPair();
        returnBean.setPrivateKey(map.get("private_key_name"));
        returnBean.setPublicKey(map.get("public_key_name"));
        JSONObject json = new JSONObject();
        json.put("appId",appid);
        json.put("appSecurity",secret);
        json.put("enterpriseSenderCode", code);

        json.put("randomPublicKey",map.get("public_key_name"));

        String url = Config.getAppLocationUrl(st);
        String ss1 = HttpUtils.sendPost(url,json.toJSONString());
//        System.out.println(ss1);
        ResBaseBean resBaseBean = JSONObject.parseObject(ss1,ResBaseBean.class);
        if(resBaseBean.getSuccess()){
            EncryptionResponse encryptionResponse = JSONObject.parseObject(resBaseBean.getData().toString(), EncryptionResponse.class);

            String info = Util.byteToHex( SM2Util.decrypt132(Util.hexToByte(map.get("private_key_name")),Util.hexToByte(encryptionResponse.getEncryptedCode())));
//            String plainText = org.jeecg.common.util.sm4.Sm4Util.decryptEcb(info, encryptionResponse.getEncryptedContent());
            //todo
            String plainText = org.jeecg.modules.api.wlhy.app.utils.SM4Util.decrypt_Ecb_Padding(info, encryptionResponse.getEncryptedContent());

            List<UrlInfo> urlInfos = JSONObject.parseArray(JSONObject.parseObject(plainText).getString("urlInfoList"),UrlInfo.class);
            returnBean.setUrlInfoBeans(urlInfos);
            returnBean.setResult(true);
        }else {
            returnBean.setResult(false);
        }

        return returnBean;
    }

    public static ResBaseBean initUploadLocation(List<LocationInfo> locationInfos, InitReturnBean init) throws Exception {
        String UrlPublicKey = init.getUrlInfoBeans().get(0).getPublicKey();
        String publicKey = init.getPublicKey();
        String privateKey = init.getPrivateKey();
        String url = init.getUrlInfoBeans().get(0).getUrl();
        String appid = init.getAppid();
        String secret = init.getSecret();
        String code = init.getCode();

        LoctationInfoRequest request = new LoctationInfoRequest();

        String tkey = UUID.randomUUID().toString().replace("-", "").substring(0, 32);
        String encryptedCode = SM2Util.encrypt132(Util.hexToByte(tkey),Util.hexToByte(UrlPublicKey));
        String data = JSONObject.toJSONString(locationInfos);
//        String encryptedContent = org.jeecg.common.util.sm4.Sm4Util.encryptEcb(tkey, data);
        //todo
        String encryptedContent = org.jeecg.modules.api.wlhy.app.utils.SM4Util.encrypt_Ecb_Padding(tkey, data);

        EncryptionResponse response = new EncryptionResponse();
        response.setEncryptedCode(encryptedCode);
        response.setEncryptedContent(encryptedContent);
        request.setData(response);
        request.setRandomPublicKey(publicKey);

        request.setAppId(appid);
        request.setAppSecurity(secret);
        request.setEnterpriseSenderCode(code);

        JSONObject json = JSONObject.parseObject(HttpUtils.sendPost(url,JSONObject.toJSONString(request)));
        ResBaseBean resBaseBean = JSONObject.parseObject(json.toString(),ResBaseBean.class);
        if(resBaseBean.getSuccess()){
            EncryptionResponse encryptionResponse = JSONObject.parseObject(resBaseBean.getData().toString(), EncryptionResponse.class);

            String info = Util.byteToHex( SM2Util.decrypt132(Util.hexToByte(privateKey),Util.hexToByte(encryptionResponse.getEncryptedCode())));
//            String plainText = org.jeecg.common.util.sm4.Sm4Util.decryptEcb(info, encryptionResponse.getEncryptedContent());
            //todo
            String plainText = org.jeecg.modules.api.wlhy.app.utils.SM4Util.decrypt_Ecb_Padding(info, encryptionResponse.getEncryptedContent());

            resBaseBean.setDatas(JSONArray.parseArray(plainText));
        }
        return resBaseBean;
    }

    public static void main(String[] args) throws Exception {


      /*  String appid="uni.UNIDA90817";
        String secret="3obuT8DiN7jwXHezKJ4zuO8zFyJIylCDKVU7Jkvd3cOyR8HzuG41yFmHMv1Qyls9";
        String code="1391130524MA0FDR3C20";*/

        String appid="com.sinoiov.zy.wccyr.luojihaoyun";
        String secret="mqcxpzqypewqdihe3bjir20dhpwvdjvhzvr8njfzwz1zz3z8vpbxr46tbt3q8o0e";
        String code="1391130501MA085KT6XA";

        //tj
       /* String appid="com.sinoiov.zy.wccyr.julianzhiyun";
        String secret="Et8XVIMOKbJQitNZfz30pfTdXog9AgyNxAALHs0uqGGkkLXPQjGlxRe2F6GmOXG";
        String code="1391130582MA0DGPP544";*/

        InitReturnBean initReturnBean = initMain(appid,secret,code,"1");

//        List<ShippingNoteInfo> list = new ArrayList<>();
//        ShippingNoteInfo info = new ShippingNoteInfo();
//        info.setAlreadySendCount(0);
//        info.setSendCount(1);
//        info.setSerialNumber("0000");
//        info.setShippingNoteNumber("YD20211226143511233");
//        info.setStartCountrySubdivisionCode("130524");
//
//        info.setEndCountrySubdivisionCode("130107");
//
//        info.setInterval(0);
//        info.setStartLocationText("泓瑞");
//        info.setStartLongitude(114.6194340);
//        info.setStartLatitude(37.5314620);
//        info.setEndLocationText("河钢石钢新区");
//        info.setEndLongitude(114.5243530);
//        info.setEndLatitude(37.3873020);
//        list.add(info);
//
//        //晚上
//        //中间点 116.013966   38.039287
//        //明天
//        //终点 117.687294   38.324723
//        LocationInfo locationInfo = new LocationInfo();
//        locationInfo.setLongitude(117.687294);
//        locationInfo.setLatitude(38.324723);
//        locationInfo.setLocationText("");
//        locationInfo.setLocationTime(System.currentTimeMillis());
//        locationInfo.setLocationType(1); //*****************************重要 0 start  1 stop 2 send 3 pause 4 restart
//        locationInfo.setRemark("备注");
//        locationInfo.setCountrySubdivisionCode("");
//
//        locationInfo.setVehicleNumber("冀A4111V");
//        locationInfo.setRandomPublicKey(initReturnBean.getPublicKey());
//        locationInfo.setLocationTime(System.currentTimeMillis());
//        locationInfo.setDriverName("李飞");
//
//        String deviceId = UUID.randomUUID().toString().replace("-", "");
//        locationInfo.setDeviceId(deviceId);
//        locationInfo.setShippingNoteInfos(list);
//        List<LocationInfo> locationInfos = new ArrayList<>();
//        locationInfos.add(locationInfo);
//
//        ResBaseBean resBaseBean = initUploadLocation(locationInfos, initReturnBean);
//        System.out.println(resBaseBean);

    }

}
